package com.quark.qpp.ps.common.util;

import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.oauth2.sdk.GrantType;
import com.quark.qpp.core.security.service.dto.SessionContext;

public class JwtUtility {

	private static String contentServiceUrl = System.getenv("content.platform.services.url");

	private static String clientId = System.getenv("auth.server.realm.clientId");

	private static String clientSecret = System.getenv("auth.server.realm.clientSecret");

	private static String userName = System.getenv("jwt.claim.user.name");

	private static final Map<String, Token> cachedTokensMap = new ConcurrentHashMap<>();

	private static final Logger logger = LoggerFactory.getLogger(JwtUtility.class);

	@Value("${token.expiry.buffer.seconds:120}")
	private static int tokenExpiryBufferSeconds;

	/**
	 * Get valid token from the Session Context.
	 */
	public static void createValidSessionContext() {
		if (userName == null) {
			throw new RuntimeException("Environment variable 'jwt.claim.user.name' is not configured.");
		}
		SessionContext sessionContext = new SessionContext();
		sessionContext.setUserName(userName);
		sessionContext.setAuthentication(new PreAuthenticatedAuthenticationToken(null, getToken(), new ArrayList<>()));
		SecurityContextHolder.setContext(sessionContext);
	}

	/**
	 * Check if the token for the required userName is present in the cache. If
	 * cached token is present and is not expired then it is returned. Else, a new
	 * token is generated and returned.
	 * 
	 * @return Token for the specified userName.
	 */
	private static String getToken() {
		if (cachedTokensMap.containsKey(userName)) {
			Token token = cachedTokensMap.get(userName);
			long currentTimestamp = Instant.now().getEpochSecond();
			if (token.getAccessTokenExpiresAt() - tokenExpiryBufferSeconds > currentTimestamp) {
				logger.debug(String.format("Using cached access token for user Name: {} on behalf of client: {}",
						userName, clientId));
				return token.getAccessToken();
			} else if (!token.getRefreshToken().isEmpty()) {
				if (token.getRefreshTokenExpiresAt() - tokenExpiryBufferSeconds > currentTimestamp) {
					return getOAuthClientToken(token.getRefreshToken());
				}
			}
		}
		return getJwtAuthenticationToken();
	}

	/**
	 * Creates a new token for the specified userName when there is no cached token
	 * available for the userName specified.
	 * 
	 * @return fresh token for specified userName
	 */
	private static String getJwtAuthenticationToken() {
		RestTemplate restTemplate = new RestTemplate();
		String url = contentServiceUrl + "/api/v3/sessionService/impersonateUser";
		url = url.replaceAll("\\.\\.\\/", "");
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		String impersonaterToken = getOAuthClientToken(null);
		headers.set("Authorization", "Bearer " + impersonaterToken);
		Map<String, String> requestBody = new HashMap<String, String>();
		requestBody.put("user_name", userName);
		requestBody.put("client_id", clientId);
		requestBody.put("client_secret", clientSecret);
		requestBody.put("impersonator_token", impersonaterToken);
		HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
		@SuppressWarnings("rawtypes")
		ResponseEntity<Map> responseEntity = restTemplate.postForEntity(url, requestEntity, Map.class);
		@SuppressWarnings("unchecked")
		Map<String, String> responseBody = responseEntity.getBody();
		ObjectMapper mapper = new ObjectMapper();
		Token token = null;
		String json;
		try {
			json = mapper.writeValueAsString(responseBody);
			token = mapper.readValue(json, Token.class);
		} catch (JsonProcessingException e) {
			logger.error("Error while generating fresh access token for userName: {} on behalf of client: {}", userName,
					clientId);
		}
		cacheToken(token);
		return responseBody.get("access_token");
	}

	/**
	 * Generates new token using client Id if no refresh token is provided. else,
	 * generate new token using refresh token provided.
	 * 
	 * @param refreshToken
	 * @return accessToken for specified userName
	 */
	@SuppressWarnings("rawtypes")
	public static String getOAuthClientToken(String refreshToken) {
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().add(0,
				(HttpMessageConverter<?>) new StringHttpMessageConverter(StandardCharsets.UTF_8));
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

		MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
		formData.add("client_id", clientId);
		formData.add("client_secret", clientSecret);
		if (refreshToken == null) {
			formData.add("grant_type", GrantType.CLIENT_CREDENTIALS.toString());
		} else {
			formData.add("grant_type", GrantType.REFRESH_TOKEN.toString());
			formData.add("refresh_token", refreshToken);
			formData.add("scope", "profile");
		}

		HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);
		String url = contentServiceUrl + "/auth/token";
		url = url.replaceAll("\\.\\.\\/", "");
		ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);
		if (refreshToken != null) {
			ObjectMapper mapper = new ObjectMapper();
			Token token = null;
			String json;
			try {
				json = mapper.writeValueAsString(responseEntity.getBody());
				token = mapper.readValue(json, Token.class);
			} catch (JsonProcessingException e) {
				logger.error("Error while refreshing cached access token for user Name: {} on behalf of client: {}",
						userName, clientId);
			}
			cacheToken(token);
		}
		return (String) responseEntity.getBody().get("access_token");
	}

	/**
	 * 
	 * @return token from security context with Bearer appended.
	 */
	public static String getJwtTokenFromContext() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication instanceof JwtAuthenticationToken) {
			JwtAuthenticationToken authenticationToken = (JwtAuthenticationToken) SecurityContextHolder.getContext()
					.getAuthentication();
			Jwt jwt = (Jwt) authenticationToken.getToken();
			return "Bearer " + jwt.getTokenValue();
		} else {
			return "Bearer " + authentication.getCredentials().toString();
		}
	}

	/**
	 * 
	 * @return token from security context without Bearer appended.
	 */
	public static String getOnlyJwtTokenFromContext() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication instanceof JwtAuthenticationToken) {
			JwtAuthenticationToken authenticationToken = (JwtAuthenticationToken) SecurityContextHolder.getContext()
					.getAuthentication();
			Jwt jwt = (Jwt) authenticationToken.getToken();
			return jwt.getTokenValue();
		} else {
			return authentication.getCredentials().toString();
		}
	}

	private static void cacheToken(Token token) {
		cachedTokensMap.put(userName, token);
	}

	/**
	 * DTO for token generated for a particular user. *
	 */
	@JsonIgnoreProperties(ignoreUnknown = true)
	private static class Token {

		@JsonProperty("access_token")
		private String accessToken;

		@JsonProperty("expires_in")
		private int expiresIn;

		@JsonProperty("refresh_expires_in")
		private int refreshExpiresIn;

		@JsonProperty("refresh_token")
		private String refreshToken;

		@JsonProperty("token_type")
		private String tokenType;

		public Token(String accessToken) {
			super();
			this.accessToken = accessToken;
		}

		public Token() {

		}

		@JsonProperty("session_state")
		private String sessionState;

		private long accessTokenExpiresAt;

		private long refreshTokenExpiresAt;

		public String getAccessToken() {
			return accessToken;
		}

		public void setAccessToken(String accessToken) {
			this.accessToken = accessToken;
		}

		public int getExpiresIn() {
			return expiresIn;
		}

		public void setExpiresIn(int expiresIn) {
			this.expiresIn = expiresIn;
			this.accessTokenExpiresAt = Instant.now().getEpochSecond() + expiresIn;
		}

		public int getRefreshExpiresIn() {
			return refreshExpiresIn;
		}

		public void setRefreshExpiresIn(int refreshExpiresIn) {
			this.refreshExpiresIn = refreshExpiresIn;
			this.refreshTokenExpiresAt = Instant.now().getEpochSecond() + refreshExpiresIn;
		}

		public String getRefreshToken() {
			return refreshToken;
		}

		public void setRefreshToken(String refreshToken) {
			this.refreshToken = refreshToken;
		}

		public String getTokenType() {
			return tokenType;
		}

		public void setTokenType(String tokenType) {
			this.tokenType = tokenType;
		}

		public String getSessionState() {
			return sessionState;
		}

		public void setSessionState(String sessionState) {
			this.sessionState = sessionState;
		}

		public long getAccessTokenExpiresAt() {
			return accessTokenExpiresAt;
		}

		public long getRefreshTokenExpiresAt() {
			return refreshTokenExpiresAt;
		}

	}
}